import React,{useEffect,useRef, useState} from 'react';
import { Box, TextField, Button, Paper, Typography, Avatar, IconButton, Popover, Grid, CircularProgress, Dialog, DialogContent, Snackbar, Alert } from '@mui/material';
import { MoreVert as MoreVertIcon, InsertEmoticon as InsertEmoticonIcon, AttachFile as AttachFileIcon, Search as SearchIcon, Close as CloseIcon } from '@mui/icons-material';
import { downloadFullImage } from '../services/ImageService';
const ChatArea = ({ messages, currentUser, selectedContact, newMessage, setNewMessage, handleSendMessage }) => {
  const messagesEndRef = useRef(null);
  const messageContainerRef = useRef(null);
  const [page, setPage] = useState(1);
  const [paginatedMessages, setPaginatedMessages] = useState([]);
  const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
  const [scrollHeight, setScrollHeight] = useState(0);
  const PAGE_SIZE = 20;
  
  // 表情选择器相关状态
  const [emojiAnchorEl, setEmojiAnchorEl] = useState(null);
  const emojiOpen = Boolean(emojiAnchorEl);
  const textFieldRef = useRef(null);
  const fileInputRef = useRef(null);
  
  // 图片上传相关状态
  const [selectedImage, setSelectedImage] = useState(null);
  const [imagePreview, setImagePreview] = useState('');
  const [isUploading, setIsUploading] = useState(false);
  
  // 图片预览弹窗相关状态
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [previewImageUrl, setPreviewImageUrl] = useState('');
  const [zoomLevel, setZoomLevel] = useState(1); // 添加缩放比例状态
  
  // 图片拖动相关状态
  const [isDragging, setIsDragging] = useState(false);
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  
  // 图片下载相关状态
  // const [downloadStatus, setDownloadStatus] = useState('');
  // const [downloadProgress, setDownloadProgress] = useState(0);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState('info');
  
  // 处理图片选择
  const handleImageSelect = (event) => {
    const file = event.target.files[0];
    if (file && file.type.startsWith('image/')) {
      setSelectedImage(file);
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  };
  
  // 取消选择的图片
  const handleCancelImage = () => {
    setSelectedImage(null);
    setImagePreview('');
    fileInputRef.current.value = '';
  };
  
  // 发送图片
  const handleSendImage = async () => {
    if (!selectedImage || !selectedContact) return;
    
    setIsUploading(true);
    try {
      // 将图片转换为Base64格式
      const reader = new FileReader();
      reader.readAsDataURL(selectedImage);
      reader.onload = async () => {
        const base64Image = reader.result.split(',')[1]; // 移除Data URL前缀
        
        // 创建一个临时消息对象，显示在UI上
        const messageId = Date.now();
        const tempMessage = {
          id: messageId,
          senderId: currentUser.wxid,
          senderName: currentUser.name,
          senderAvatar: currentUser.avatar,
          content: imagePreview, // 使用预览URL作为临时内容
          timestamp: new Date().toISOString(),
          status: 'pending',
          msgType: 3, // 3表示图片消息
          tag:'send'
        };
        
        // 将临时消息添加到消息列表
        handleSendMessage(tempMessage,base64Image);
        
        // 清理图片选择状态
        handleCancelImage();
      };
    } catch (error) {
      console.error('处理图片失败:', error);
    } finally {
      setIsUploading(false);
    }
  };
  
  // 表情分类
  const emojiCategories = {
    '常用表情': ['😀', '😁', '😂', '🤣', '😃', '😄', '😅', '😆', '😉', '😊', '😋', '😎', '😍', '😘', '🥰'],
    '手势': ['👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '🤙', '👋', '🙏', '👏', '🙌', '👐', '🤲', '🤝'],
    '表情': ['😗', '😙', '😚', '🙂', '🤗', '🤔', '🤨', '😐', '😑', '😶', '🙄', '😏', '😣', '😥', '😮'],
    '情绪': ['🤐', '😯', '😪', '😫', '🥱', '😴', '😌', '😛', '😜', '😝', '🤤', '😒', '😓', '😔', '😕'],
    '消极': ['🙃', '🤑', '😲', '☹️', '🙁', '😖', '😞', '😟', '😤', '😢', '😭', '😦', '😧', '😨', '😩'],
    '其他': ['🤯', '😬', '😰', '😱', '🥵', '🥶', '😳', '🤪', '😵', '🥴', '😠', '😡', '🤬', '😷', '🤒']
  };
  
  // 当前选中的表情分类
  const [currentCategory, setCurrentCategory] = useState('常用表情');
  
  // 处理表情图标点击
  const handleEmojiIconClick = (event) => {
    setEmojiAnchorEl(event.currentTarget);
  };
  
  // 处理表情选择器关闭
  const handleEmojiClose = () => {
    setEmojiAnchorEl(null);
    // 关闭后聚焦输入框
    setTimeout(() => {
      textFieldRef.current?.focus();
    }, 0);
  };
  
  // 处理表情选择
  const handleEmojiSelect = (emoji) => {
    setNewMessage(prev => prev + emoji);
    // 选择表情后自动关闭弹窗
    handleEmojiClose();
  };
  
  // 处理表情分类切换
  const handleCategoryChange = (category) => {
    setCurrentCategory(category);
  };
  
  // 分页处理消息
  useEffect(() => {
    if (messages && messages.length > 0) {
      const startIndex = Math.max(0, messages.length - PAGE_SIZE * page);
      const endIndex = messages.length;
      setPaginatedMessages(messages.slice(startIndex, endIndex));
      
      // 记录当前滚动高度，用于加载更多消息后保持位置
      if (messageContainerRef.current && page > 1) {
        setScrollHeight(messageContainerRef.current.scrollHeight);
      }
    } else {
      // 当没有消息时，重置分页消息为空数组
      setPaginatedMessages([]);
    }
  }, [messages, page]);
  
  useEffect(() => {
    setPage(1);
  }, [selectedContact]);
  
  // 滚动事件处理
  const handleScroll = (e) => {
    const { scrollTop } = e.target;
    
    // 当用户向上滚动到顶部时，加载更多历史消息
    if (scrollTop === 0 && messages.length > paginatedMessages.length) {
      // 记录当前滚动容器的高度，用于后续保持位置
      setScrollHeight(e.target.scrollHeight);
      setPage(prev => prev + 1);
      setShouldAutoScroll(false);
    }
    
    // 当用户滚动到底部时，启用自动滚动
    const isAtBottom = e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight < 10;
    if (isAtBottom) {
      setShouldAutoScroll(true);
    } else {
      setShouldAutoScroll(false);
    }
  };
  
  // 处理滚动位置
  useEffect(() => {
    if (!messageContainerRef.current) return;
    
    // 切换联系人时，总是滚动到最新消息
    if (selectedContact) {
      if (shouldAutoScroll) {
        messagesEndRef.current?.scrollIntoView({ behavior: 'auto' });
      } else if (page > 1 && scrollHeight > 0) {
        // 加载更多历史消息时，保持用户的阅读位置
        const newScrollHeight = messageContainerRef.current.scrollHeight;
        const scrollDiff = newScrollHeight - scrollHeight;
        messageContainerRef.current.scrollTop = scrollDiff > 0 ? scrollDiff : 0;
      }
    }
  }, [paginatedMessages, selectedContact, page, scrollHeight, shouldAutoScroll]);
  
  // 监听消息列表变化，自动滚动到最新消息
  useEffect(() => {
    // 当消息列表更新且应该自动滚动时，滚动到最新消息
    if (messages && messages.length > 0 && shouldAutoScroll) {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, shouldAutoScroll]);
  
  // 当发送新消息时，确保滚动到底部
  useEffect(() => {
    // 如果newMessage被清空，说明消息刚刚被发送
    if (newMessage === '' && messagesEndRef.current) {
      // 使用setTimeout确保在DOM更新后执行滚动
      setTimeout(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    }
  }, [newMessage]);
  // 格式化时间显示
  const formatTime = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  if (!selectedContact) {
    return (
      <Box sx={{ 
        flex: 1, 
        display: 'flex', 
        flexDirection: 'column', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100%',
        bgcolor: '#f5f5f5'
      }}>
        <Typography variant="body1" color="textSecondary">
          请从左侧选择联系人开始聊天
        </Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* 聊天头部 */}
      <Box sx={{ 
        display: 'flex', 
        alignItems: 'center', 
        p: 1.3, 
        borderBottom: '1px solid #e8e8e8',
        bgcolor: '#f5f5f5'
      }}>
        {/* <Avatar src={selectedContact?.avatar} alt={selectedContact?.name} /> */}
        <Typography variant="h6" sx={{ ml: 2 }}>{selectedContact?.name}</Typography>
      </Box>

      {/* 消息区域 */}
      <Box 
      ref={messageContainerRef}
      sx={{ 
        flex: 1, 
        overflowY: 'auto', 
        p: 2,
        bgcolor: '#fafafa'
      }}
      onScroll={handleScroll}
    >
        {paginatedMessages && paginatedMessages.length > 0 ? (
          paginatedMessages.map((message, index) => (
            <Box 
              key={index}
              sx={{ 
                display: 'flex',
                justifyContent: message.senderId === currentUser.wxid ? 'flex-end' : 'flex-start',
                mb: 2
              }}
            >
                  {message.senderId !== currentUser.wxid && (
                    <Avatar
                      src={message.senderAvatar}
                      alt={message.senderName}
                      sx={{ mr: 1, width: 36, height: 36 }}
                    />
                  )}
                  <Box sx={{ maxWidth: '80%', width: 'auto', overflow: 'hidden' }}>
                    {message.isGroupMessage && message.senderId !== currentUser.wxid && (
                      <Typography variant="caption" sx={{ display: 'block', mb: 0.5, color: '#666' }}>
                        {message.displayName || message.senderName}
                      </Typography>
                    )}
                  <Paper
                      elevation={0}
                      sx={{
                        p: 1.5,
                        borderRadius: message.senderId === currentUser.wxid ? '4px 0px 4px 4px' : '0px 4px 4px 4px',
                        backgroundColor: message.senderId === currentUser.wxid && message.msgType!==3? '#95ec69' : 'white',
                        color: 'black',
                        position: 'relative',
                        '&::before': message.senderId === currentUser.wxid && message.msgType!==3? {
                          content: '""',
                          position: 'absolute',
                          top: 0,
                          right: -6,
                          width: 0,
                          height: 0,
                          borderTop: '6px solid #95ec69',
                          borderRight: '6px solid transparent',
                        } : {
                          content: '""',
                          position: 'absolute',
                          top: 0,
                          left: -6,
                          width: 0,
                          height: 0,
                          borderTop: '6px solid white',
                          borderLeft: '6px solid transparent',
                        }
                      }}
                    >
                      {message.msgType === 3 ? (
                        <Box 
                          sx={{ 
                            cursor: 'pointer',
                            color: message.senderId === currentUser.wxid ? 'inherit' : 'primary.main',
                            fontWeight: 'medium',
                            '&:hover': { textDecoration: 'underline' }
                          }}
                          onClick={() => {
                            // 如果消息中有图片内容，则预览图片
                            if (message.content && message.content.startsWith('data:')) {
                              setPreviewImageUrl(message.content);
                              setPreviewDialogOpen(true);
                              
                            } else {
                              // 否则下载图片
                              setSnackbarMessage('正在下载图片...');
                              setSnackbarSeverity('info');
                              setSnackbarOpen(true);
                              
                              // 状态回调函数
                              const handleDownloadStatus = (status, data) => {
                                if (status === 'downloading') {
                                  if (data && data.progress) {
                                    setSnackbarMessage(`下载中: ${Math.round(data.progress)}%`);
                                  } else {
                                    setSnackbarMessage('正在下载图片...');
                                  }
                                  setSnackbarSeverity('info');
                                  setSnackbarOpen(true);
                                } else if (status === 'downloaded') {
                                  // 当图片下载完成时，如果返回的是base64数据，则更新消息对象并显示图片
                                  if (typeof data === 'string' && data.startsWith('data:')) {
                                    // 更新消息列表中的图片内容
                                    setPaginatedMessages(prevMessages => {
                                      return prevMessages.map(msg => {
                                        if (msg.id === message.id && msg.senderId === message.senderId) {
                                          return { ...msg, content: data };
                                        }
                                        return msg;
                                      });
                                    });
                                    
                                    // 更新主消息数组中的图片内容，并保存到IndexedDB
                                    // 通过调用父组件传递的handleSendMessage方法，更新主消息数组
                                    // 创建一个更新后的消息对象
                                    const updatedMessage = {
                                      ...message,
                                      content: data,
                                      status: 'success'
                                    };
                                    
                                    // 调用父组件的handleSendMessage方法，传入更新后的消息对象
                                    // 第二个参数为null，表示不需要发送图片，只需要更新本地消息
                                    handleSendMessage(updatedMessage, null, true);
                                    
                                    // 显示图片预览
                                    setPreviewImageUrl(data);
                                    setPreviewDialogOpen(true);
                                  }
                                  
                                  setSnackbarMessage('图片下载成功');
                                  setSnackbarSeverity('success');
                                  setSnackbarOpen(true);
                                } else if (status === 'failed') {
                                  setSnackbarMessage(`下载失败: ${data?.message || '未知错误'}`);
                                  setSnackbarSeverity('error');
                                  setSnackbarOpen(true);
                                }
                              };
                              
                              // 调用下载函数
                              downloadFullImage(
                                message.senderId,
                                message.id,
                                message.recipientId || currentUser.wxid,
                                handleDownloadStatus
                              ).catch(error => {
                                console.error('下载图片失败:', error);
                                setSnackbarMessage(`下载失败: ${error.message}`);
                                setSnackbarSeverity('error');
                                setSnackbarOpen(true);
                              });
                            }
                          }}
                        >
                          [图片消息]
                        </Box>
                      ) : message.msgType === 49 && message.quoteInfo ? (
                        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, maxWidth: '100%', overflow: 'hidden' }}>
                          {/* 引用消息内容 */}
                          <Box 
                            sx={{ 
                              p: 1.5, 
                              borderRadius: 1, 
                              bgcolor: 'rgba(0, 0, 0, 0.04)',
                              borderLeft: '3px solid #07c160',
                              mb: 1,
                              maxWidth: '100%',
                              width: '100%',
                              boxSizing: 'border-box'
                            }}
                          >
                            <Typography 
                              variant="caption" 
                              sx={{ 
                                display: 'block', 
                                color: '#666', 
                                fontWeight: 'medium',
                                mb: 0.5,
                                maxWidth: '100%',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis'
                              }}
                            >
                              {message.quoteInfo.referSenderName || '引用消息'}
                            </Typography>
                            <Typography 
                              variant="body2" 
                              sx={{ 
                                color: '#666',
                                fontSize: '0.8125rem',
                                whiteSpace: 'pre-wrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                display: '-webkit-box',
                                WebkitLineClamp: 2,
                                WebkitBoxOrient: 'vertical',
                                maxWidth: '100%',
                                wordBreak: 'break-word'
                              }}
                            >
                              {message.quoteInfo.referContent || '原始消息内容不可用'}
                            </Typography>
                          </Box>
                          {/* 当前消息内容 */}
                          <Typography variant="body1" sx={{ fontSize: '0.875rem', whiteSpace: 'pre-wrap' }}>
                            {message.content}
                          </Typography>
                        </Box>
                      ) : (
                        <Typography variant="body1" sx={{ fontSize: '0.875rem', whiteSpace: 'pre-wrap' }}>{message.content}</Typography>
                      )}
                    </Paper>
                    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: message.senderId === currentUser.wxid ? 'flex-end' : 'flex-start', mt: 0.5 }}>
                      {message.senderId === currentUser.wxid && message.status && (
                        <Typography variant="caption" sx={{ mr: 0.5, color: message.status === 'failed' ? '#f44336' : (message.status === 'pending' ? '#ff9800' : '#4caf50') }}>
                          {message.status === 'pending' ? '发送中' : (message.status === 'failed' ? '发送失败' : '')}
                        </Typography>
                      )}
                      <Typography variant="caption" sx={{ color: '#999', fontSize: '0.75rem' }}>
                        {formatTime(message.timestamp)}
                      </Typography>
                    </Box>
              </Box>
              {message.senderId === currentUser.wxid && (
                    <Avatar
                      src={message.senderAvatar}
                      alt={message.senderName}
                      sx={{ ml: 1, width: 36, height: 36 }}
                    />
                  )}
            </Box>
          ))
        ) : (
          <Box sx={{ 
            display: 'flex', 
            flexDirection: 'column', 
            justifyContent: 'center', 
            alignItems: 'center', 
            height: '100%'
          }}>
            <Typography variant="body1" color="textSecondary">
              暂无聊天记录
            </Typography>
          </Box>
        )}
        <div ref={messagesEndRef} />
      </Box>

      {/* 输入区域 */}
      <Box sx={{ p: 2, borderTop: '1px solid #d9d9d9', bgcolor: '#f5f5f5' }}>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <IconButton size="small" sx={{ p: 0.5 }}>
                  <MoreVertIcon fontSize="small" />
                </IconButton>
                <IconButton size="small" sx={{ p: 0.5 }}>
                  <SearchIcon fontSize="small" />
                </IconButton>
                <IconButton 
                  size="small" 
                  sx={{ p: 0.5 }}
                  onClick={handleEmojiIconClick}
                  aria-describedby="emoji-popover"
                >
                  <InsertEmoticonIcon fontSize="small" />
                </IconButton>
                
                {/* 表情选择器弹出框 */}
                <Popover
                  id="emoji-popover"
                  open={emojiOpen}
                  anchorEl={emojiAnchorEl}
                  onClose={handleEmojiClose}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'left',
                  }}
                  transformOrigin={{
                    vertical: 'bottom',
                    horizontal: 'left',
                  }}
                  sx={{ mt: -1 }}
                >
                  <Box sx={{ width: 420, maxHeight: 300 }}>
                    {/* 表情分类选择器 */}
                    <Box sx={{ 
                      display: 'flex', 
                      borderBottom: '1px solid #eaeaea',
                      bgcolor: '#f5f5f5'
                    }}>
                      {Object.keys(emojiCategories).map((category) => (
                        <Box 
                          key={category}
                          onClick={() => handleCategoryChange(category)}
                          sx={{
                            px: 1.5,
                            py: 1,
                            fontSize: '0.85rem',
                            cursor: 'pointer',
                            color: currentCategory === category ? 'primary.main' : 'text.secondary',
                            borderBottom: currentCategory === category ? '2px solid #07c160' : '2px solid transparent',
                            '&:hover': { bgcolor: 'rgba(0, 0, 0, 0.04)' }
                          }}
                        >
                          {category}
                        </Box>
                      ))}
                    </Box>
                    
                    {/* 表情列表 */}
                    <Box sx={{ p: 1.5, maxHeight: 240, overflowY: 'auto' }}>
                      <Grid container spacing={0.5}>
                        {emojiCategories[currentCategory].map((emoji, index) => (
                          <Grid item key={index}>
                            <IconButton 
                              size="small" 
                              onClick={() => handleEmojiSelect(emoji)}
                              sx={{ 
                                fontSize: '1.5rem',
                                p: 0.5,
                                minWidth: '40px',
                                minHeight: '40px',
                                '&:hover': { bgcolor: 'rgba(0, 0, 0, 0.04)' }
                              }}
                            >
                              {emoji}
                            </IconButton>
                          </Grid>
                        ))}
                      </Grid>
                    </Box>
                  </Box>
                </Popover>
                <IconButton 
                  size="small" 
                  sx={{ p: 0.5 }}
                  onClick={() => fileInputRef.current?.click()}
                >
                  <AttachFileIcon fontSize="small" />
                </IconButton>
                <input
                  type="file"
                  ref={fileInputRef}
                  accept="image/*"
                  style={{ display: 'none' }}
                  onChange={handleImageSelect}
                />
              </Box>
            </Box>
            {imagePreview ? (
              <Box sx={{ 
                position: 'relative', 
                width: '100%', 
                minHeight: '120px',
                border: '1px solid #e0e0e0',
                borderRadius: '4px',
                p: 1,
                mb: 1,
                bgcolor: '#f5f5f5'
              }}>
                <IconButton 
                  size="small" 
                  sx={{ 
                    position: 'absolute', 
                    top: 8, 
                    right: 8, 
                    bgcolor: 'rgba(0,0,0,0.5)',
                    color: 'white',
                    '&:hover': {
                      bgcolor: 'rgba(0,0,0,0.7)'
                    },
                    zIndex: 1
                  }}
                  onClick={handleCancelImage}
                >
                  <CloseIcon fontSize="small" />
                </IconButton>
                <Box sx={{ 
                  display: 'flex', 
                  justifyContent: 'center', 
                  alignItems: 'center',
                  height: '100%',
                  maxHeight: '300px',
                  overflow: 'hidden'
                }}>
                  <img 
                    src={imagePreview} 
                    alt="图片预览" 
                    style={{ 
                      maxWidth: '100%', 
                      maxHeight: '300px', 
                      objectFit: 'contain' 
                    }} 
                  />
                </Box>
                <Box sx={{ 
                  display: 'flex', 
                  justifyContent: 'flex-end', 
                  mt: 1 
                }}>
                  {isUploading ? (
                    <CircularProgress size={24} sx={{ mr: 1 }} />
                  ) : (
                    <Button 
                      variant="contained" 
                      color="primary" 
                      size="small"
                      onClick={handleSendImage}
                      disabled={isUploading}
                    >
                      发送图片
                    </Button>
                  )}
                </Box>
              </Box>
            ) : (
              <TextField
                fullWidth
                placeholder="输入消息..."
                variant="outlined"
                value={newMessage}
                onChange={(e) => setNewMessage(e.target.value)}
                onKeyPress={(e) => {
                  if (e.key === 'Enter' && !e.altKey) {
                    e.preventDefault();
                    handleSendMessage();
                  } else if (e.key === 'Enter' && e.altKey) {
                    setNewMessage(prev => prev + '\n');
                  }
                }}
                multiline
                minRows={3}
                maxRows={8}
                inputRef={textFieldRef}
                autoFocus
                className="animated-input"
                sx={{
                  '& .MuiOutlinedInput-root': {
                    borderRadius: '8px',
                    bgcolor: '#ffffff',
                    minHeight: '120px',
                    transition: 'all 0.3s ease',
                    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
                    '& fieldset': {
                      borderColor: 'rgba(0, 0, 0, 0.1)',
                    },
                    '&:hover fieldset': {
                      borderColor: 'rgba(126, 217, 87, 0.5)',
                    },
                    '&.Mui-focused': {
                      boxShadow: '0 4px 12px rgba(126, 217, 87, 0.15)',
                      transform: 'translateY(-2px)',
                      '& fieldset': {
                        borderColor: '#7ed957',
                        borderWidth: '2px',
                      },
                    },
                  },
                  '& .MuiInputBase-input': {
                    fontSize: '0.95rem',
                    color: '#333333',
                  },
                  '& .MuiInputBase-input::placeholder': {
                    color: 'rgba(0, 0, 0, 0.4)',
                    opacity: 1,
                  },
                }}
              />
            )}
          </Box>

      {/* 图片预览弹窗 */}
      <Dialog
        open={previewDialogOpen}
        onClose={() => {
          setPreviewDialogOpen(false);
          setZoomLevel(1); // 关闭弹窗时重置缩放级别
          setDragPosition({ x: 0, y: 0 }); // 关闭弹窗时重置拖动位置
          setIsDragging(false); // 重置拖动状态
        }}
        maxWidth="xl"
        fullWidth
        PaperProps={{
          sx: {
            bgcolor: 'rgba(0, 0, 0, 0.8)',
            boxShadow: 'none',
            borderRadius: 2,
            position: 'relative',
            maxHeight: '90vh',
            height: '90vh'
          }
        }}
      >
        <IconButton
          onClick={() => {
            setPreviewDialogOpen(false);
            setZoomLevel(1); // 关闭弹窗时重置缩放级别
            setDragPosition({ x: 0, y: 0 }); // 关闭弹窗时重置拖动位置
            setIsDragging(false); // 重置拖动状态
          }}
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            color: 'white',
            bgcolor: 'rgba(0, 0, 0, 0.2)',
            '&:hover': {
              bgcolor: 'rgba(0, 0, 0, 0.7)'
            },
            zIndex: 1
          }}
        >
          <CloseIcon />
        </IconButton>
        <DialogContent 
          sx={{ 
            p: 0, 
            overflow: 'auto', 
            display: 'flex', 
            justifyContent: 'center', 
            alignItems: 'center', 
            backgroundColor: 'transparent',
            cursor: isDragging ? 'grabbing' : 'grab',
            height: '100%',
            '&::-webkit-scrollbar': {
              width: '8px',
              height: '8px'
            },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: 'rgba(255, 255, 255, 0.3)',
              borderRadius: '4px'
            },
            '&::-webkit-scrollbar-track': {
              backgroundColor: 'transparent'
            }
          }}
          onWheel={(e) => {
            // 根据滚轮方向调整缩放级别
            const delta = e.deltaY < 0 ? 0.1 : -0.1;
            setZoomLevel(prevZoom => {
              // 限制缩放范围在0.5到3之间
              const newZoom = Math.max(0.5, Math.min(3, prevZoom + delta));
              return newZoom;
            });
          }}
          onMouseMove={(e) => {
            if (isDragging) {
              // 计算拖动的距离
              const deltaX = e.clientX - dragStart.x;
              const deltaY = e.clientY - dragStart.y;
              
              // 更新图片位置
              setDragPosition({
                x: dragPosition.x + deltaX,
                y: dragPosition.y + deltaY
              });
              
              // 更新拖动起始点
              setDragStart({
                x: e.clientX,
                y: e.clientY
              });
            }
          }}
          onMouseUp={() => {
            setIsDragging(false);
          }}
          onMouseLeave={() => {
            setIsDragging(false);
          }}
        >
          <Box
            sx={{
              width: '100%',
              height: '100%',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              overflow: 'auto'
            }}
          >
            <img
              src={previewImageUrl}
              alt="预览图片"
              style={{
                width: `${100 * zoomLevel}%`,
                height: 'auto',
                objectFit: 'contain',
                transition: isDragging ? 'none' : 'transform 0.1s ease-out',
                maxWidth: 'none',
                maxHeight: 'none',
                transform: `translate(${dragPosition.x}px, ${dragPosition.y}px)`,
                userSelect: 'none'
              }}
              onMouseDown={(e) => {
                // 阻止默认行为和冒泡
                e.preventDefault();
                
                // 设置拖动状态
                setIsDragging(true);
                
                // 记录拖动起始点
                setDragStart({
                  x: e.clientX,
                  y: e.clientY
                });
              }}
              draggable="false"
            />
          </Box>
        </DialogContent>
      </Dialog>
      
      {/* 下载状态提示 */}
      <Snackbar 
        open={snackbarOpen} 
        autoHideDuration={6000} 
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={() => setSnackbarOpen(false)} 
          severity={snackbarSeverity} 
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default ChatArea;